import axios from "axios";
import config from "@/config.js";
import message from "@/components/message/index.js";

const webapi = axios.create({
  baseURL: config.apiBaseUrl,
  timeout: 30000,
});

webapi.interceptors.request.use(
  function (requestConfig) {
  
    return requestConfig;
  },
  function (error) {

    return Promise.reject(error);
  }
);

webapi.interceptors.response.use(
  function (res) {
    const resData = res.data;
    // 二进制数据则直接返回
    if (res.request.responseType == "blob" || res.request.responseType == "arraybuffer") {
      return resData;
    }

    const code = resData.code;
    const msg = resData.message;

    if (code == 200) {
      return resData;
    } else if (code == 400) {
      return Promise.reject(msg);
    } else if (code == 500) {
      return Promise.reject(msg);
    } else {
      return Promise.reject("unknown error");
    }
  },
  function (error) {
    message(error.message, "error");
    return Promise.reject(error);
  }
);

export default webapi;
